import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import store from '@/store'
import qs from 'qs'
import {getBaseUri} from '@/utils/auth'

// const BASE_URI = process.env.NODE_ENV === 'production' ? window.location.origin +'/xxx/' : process.env.BASE_API
// create an axios instance
const service = axios.create({
  baseURL: getBaseUri(),
  timeout: process.env.TIME_OUT
})

// request interceptor
service.interceptors.request.use(
    config => {
      // Do something before request is sent
      if (store.getters.token) {
        // config.headers['X-Token'] = getToken()
      }
      if (config.data && !(config.data instanceof FormData)) {
        config.data = config.data ? qs.stringify(config.data) : ''
      }
      config.withCredentials = true
      // config.url = config.url + '.action'
      return config
    },
    error => {
      // Do something with request error
      console.log(error) // for debug
      Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    // response => response,
    /**
     * 下面的注释为通过在response里，自定义code来标示请求状态
     * 当code返回如下情况则说明权限有问题，登出并返回到登录页
     * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中
     * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
     */
    response => {
      const contenType = response.headers['content-type']
      if (!contenType) {
        return null
      } else if (contenType.indexOf('json') === -1) {
        if (contenType.indexOf("noautodownload") !== -1){
          //标注不要自动下载文件
          return response
        }
        // 下载处理
        const filename = response.headers['content-disposition']
        const isdownload = contenType.indexOf('download') !== -1 || contenType.indexOf('ms-excel') !== -1 ||
            contenType.indexOf('octet-stream') !== -1 || contenType.indexOf('force-download') !== -1
        if (filename || isdownload) {
          let fn = decodeURIComponent(filename.split('filename=')[1])
          const blob = new Blob([response.data])
          if (window.navigator.msSaveOrOpenBlob) {
            // 兼容ie
            window.navigator.msSaveBlob(blob, fn)
          } else {
            var downloadElement = document.createElement('a')
            var href = window.URL.createObjectURL(blob)
            downloadElement.href = href
            downloadElement.download = fn
            document.body.appendChild(downloadElement)
            // 此写法兼容火狐
            let evt = document.createEvent('MouseEvents')
            evt.initEvent('click', false, false)
            downloadElement.dispatchEvent(evt)
            document.body.removeChild(downloadElement)
            window.URL.revokeObjectURL(href)
          }
        } else {
          return response
        }
      } else {
        // json格式的返回类型才走下面的步骤
        let res = response.data
        var isBlob = res instanceof Blob
        if (isBlob) {
          var reader = new FileReader()
          reader.addEventListener('loadend', function (e) {
            var json = e.target.result
            res = JSON.parse(json)
            if (res.status !== true) {
              Message({
                message: res.message,
                type: 'error',
                duration: 5 * 1000
              })
              // 401:Token过期 或 未登录
              if (res.code == '401') {
                // 请自行在引入 MessageBox
                // import { Message, MessageBox } from 'element-ui'
                MessageBox.confirm('你已被登出，是否重新登录？', '提示', {
                  confirmButtonText: '重新登录',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  store.dispatch('FedLogOut').then(() => {
                    location.reload() // 为了重新实例化vue-router对象 避免bug
                  })
                })
              }
              // eslint-disable-next-line prefer-promise-reject-errors
              return Promise.reject('error')
            } else {
              return response.data
            }
          })
          reader.readAsText(res)
        } else {
          if (res.status !== true) {
            Message({
              message: res.message,
              type: 'error',
              duration: 5 * 1000
            })

            // 402手动登出
            if (res.code == '402') {
              store.dispatch('FedLogOut').then(() => {
                location.reload()
              })
            } else if (res.code == '401') {
              // 401:Token过期 或 未登录
              MessageBox.confirm('你已被登出，是否重新登录？', '提示', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                store.dispatch('FedLogOut').then(() => {
                  location.reload() // 为了重新实例化vue-router对象 避免bug
                })
              })
            }
            // eslint-disable-next-line prefer-promise-reject-errors
            return Promise.reject('error')
          } else {
            return response.data
          }
        }
      }
    },
    error => {
      console.log('err' + error) // for debug
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
)

export default service
